<template>
  <rt-view>
    <rt-form ref="insertForm" :model="insertForm" :rules="rules">
      <rt-header>
        <rt-list-header>
          <rt-header-icon slot="icon" icon="rt-base-account" />
          <rt-header-title title="文章分类" />
          <template slot="btn">
            <rt-header-button-group v-if="addAndUpdate">
              <rt-button icon-name="rt-base-close" @click="deactivate">
                停用
              </rt-button>
              <rt-button icon-name="rt-portal-able" @click="activate"
                >激活</rt-button
              >
            </rt-header-button-group>
            <!--更新保存-->
            <rt-button
              v-if="addAndUpdate"
              type="primary"
              icon-name="rt-base-save"
              style="margin-left: 10px"
              @click="update()"
              >保存</rt-button
            >
            <!--新建保存-->
            <rt-button
              v-if="!addAndUpdate"
              type="primary"
              icon-name="rt-base-save"
              style="margin-left: 10px"
              @click="save()"
              >保存</rt-button
            >
            <rt-button
              type="back"
              icon-name="rt-base-back"
              style="margin-left: 10px"
              @click="backArticleTypeList()"
              >返回</rt-button
            >
          </template>
        </rt-list-header>
      </rt-header>
      <rt-content>
        <rt-card>
          <rt-section>
            <rt-form-wrapper>
              <rt-row :gutter="32">
                <rt-col :span="8">
                  <rt-form-item label="分类名称" required prop="name">
                    <rt-input
                      v-model="insertForm.name"
                      placeholder="最多支持6个字"
                    />
                  </rt-form-item>
                </rt-col>
                <rt-col :span="8">
                  <rt-form-item label="序号" prop="seq">
                    <rt-input v-model="insertForm.seq" placeholder="请输入" />
                  </rt-form-item>
                </rt-col>
              </rt-row>
            </rt-form-wrapper>
          </rt-section>
        </rt-card>
      </rt-content>
    </rt-form>
  </rt-view>
</template>

<script>
import RtSection from 'vue-xpc/src/components/section/rtSection';
import util from '@/libs/util';
export default {
  name: 'ArticleEdit',
  components: { RtSection },
  data() {
    var validateSeq = (rule, value, callback) => {
      const num = /^[0-9]*$/;
      if (value) {
        if (!num.test(value)) {
          callback(new Error('请输入整数'));
        } else {
          callback();
        }
      }
      callback();
    };
    return {
      //判断添加还是更新
      //true为更新，false为新增
      addAndUpdate: false,
      id: '',
      isSure: false,
      insertForm: {
        name: '',
        seq: ''
      },
      insertFormConfirm: '',
      rules: {
        name: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: ['blur', 'change']
          },
          { max: 6, message: '最大长度为6个字符', trigger: ['blur', 'change'] }
        ],
        seq: [
          {
            required: false,
            validator: validateSeq,
            trigger: ['blur', 'change']
          }
        ]
      }
    };
  },
  watch: {
    insertForm: {
      //监听表单元素变化，变了返回就要确认
      handler(val) {
        if (val) {
          this.isSure = true;
        }
      },
      deep: true
    }
  },
  mounted() {
    this.addAndUpdate = this.$route.query.addAndUpdate;
    this.id = this.$route.query.id;
    if (this.id != null && this.id !== '') {
      this.getArticleTypeById(this.id);
    }
  },
  methods: {
    getArticleTypeById(id) {
      rt.get('/api/bbs/articletype/detail/' + id).then(res => {
        this.insertForm = res;
        this.insertFormConfirm = JSON.stringify(res);
      });
    },
    //更新保存
    update() {
      this.$refs.insertForm.$children[0].validate(valid => {
        if (valid) {
          if (this.insertFormConfirm === JSON.stringify(this.insertForm)) {
            rt.showErrorToast('数据未改变');
          } else {
            this.$confirm('确定保存分类?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                rt.post('/api/bbs/articletype/update', this.insertForm)
                  .then(res => {
                    if (res.ErrorCode === 0) {
                      rt.showSuccessToast('成功');
                      this.$router.push({ path: '/articletype/list' });
                    }
                  })
                  .catch(error => {
                    rt.showErrorToast(error);
                  });
              })
              .catch(() => {});
          }
        } else {
          return false;
        }
      });
    },
    //新建保存
    save() {
      this.$refs.insertForm.$children[0].validate(valid => {
        if (valid) {
          this.$confirm('确定保存分类?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              rt.post('/api/bbs/articletype/create', this.insertForm)
                .then(res => {
                  if (res.ErrorCode === 0) {
                    rt.showSuccessToast('成功');
                    this.$router.push({ path: '/articletype/list' });
                  }
                })
                .catch(error => {
                  rt.showErrorToast(error);
                });
            })
            .catch(() => {});
        } else {
          return false;
        }
      });
    },
    //激活
    activate() {
      const idList = [];
      idList.push(this.id);
      rt.post('/api/bbs/articletype/activate', idList)
        .then(res => {
          if (res.ErrorCode === 0) {
            rt.showSuccessToast('激活成功');
            this.$router.push({ path: '/articletype/list' });
          }
        })
        .catch(error => {
          rt.showErrorToast(error);
        });
    },
    //禁用
    deactivate() {
      const idList = [];
      idList.push(this.id);
      rt.post('/api/bbs/articletype/deactivate', idList)
        .then(res => {
          if (res.ErrorCode === 0) {
            rt.showSuccessToast('禁用成功');
            this.$router.push({ path: '/articletype/list' });
          }
        })
        .catch(error => {
          rt.showErrorToast(error);
        });
    },
    //返回
    backArticleTypeList() {
      if (this.isSure && !this.addAndUpdate) {
        this.backSure();
      } else if (
        this.addAndUpdate &&
        this.insertFormConfirm !== JSON.stringify(this.insertForm)
      ) {
        this.backSure();
      } else {
        this.backOnly();
      }
    },
    backSure() {
      this.$confirm(
        '分类未保存，返回后编辑内容将不保存，是否确定返回',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$router.push({ path: '/articletype/list' });
        })
        .catch(() => {});
    },
    backOnly() {
      this.$router.push({ path: '/articletype/list' });
    }
  }
};
</script>

<style scoped></style>
